package com.googlecode.jvmpart.proc.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.googlecode.jvmpart.proc.AbsProcessor;
import com.googlecode.jvmpart.proc.JvmProcessException;

public abstract class ConnProcessor extends AbsProcessor{
	private static final Log logger = LogFactory.getLog(ConnProcessor.class);
	private Connection conn;
	public void doExecute() throws JvmProcessException {
		Map<String, String> params = getParams();
		String jdbcUrl = params.remove(JDBC_URL);
		String jdbcUser = params.remove(JDBC_USER);
		String jdbcPassword = params.remove(JDBC_PASSWORD);
		String jdbcDriver = params.remove(JDBC_DRIVER);
		try {
			Class.forName(jdbcDriver);
			conn = DriverManager.getConnection (jdbcUrl, jdbcUser, jdbcPassword);
			conn.setAutoCommit(false);
			doProcess();
		} catch(Exception e) {
			logger.error(e, e);
			throw new JvmProcessException("root error", e);
		} finally {
			try {
				if(conn!=null) conn.close();
			} catch(Exception e) {};
		}
	}
	public abstract void doProcess() throws JvmProcessException;
	public Connection getConn() {
		return conn;
	}
	public int[] jdbcUpdate(String sql, PreparedStatementSetter setter) throws SQLException{
		PreparedStatement ps = null;
		try {
			conn = getConn();
			ps = conn.prepareStatement(sql);
			int i=0;
			for(;i<setter.getChunkSize();i++) {
				setter.setValues(ps, i);
				ps.addBatch();
			}
			return ps.executeBatch();
		} finally {
			try {
				if(ps!=null) ps.close();
			} catch(Exception e) {};
		}		
	}

}
